<?php

class Application_Model_SalesrepMapper {
	
	protected $_connection;
	
	public function __construct() {
		$this->_connection = new Application_Model_DbTable_Salesrep();
	}
	
/**
	 * 
	 * @return array result
	 */
	public function getAll($type = null) {
		try {
			$result = $this->_connection->fetchAll()->toArray();
		} catch ( Exception $e ) {
			echo $e->getMessage();
		}
		
		if($type == 'form') {
			$entries = array();
				
			foreach($result as $row) {
				$entries[$row['id']] = $row['salesRepName'];
			}
			return $entries;
			die;
		}
	
		return $result;
	}
	

	
	/**
	 * Add a salesrep name to tbl_salesRepName
	 * @param array $data
	 * 
	 */
	public function add($data) {
		
		try {
			$result = $this->_connection->insert($data);
		} catch ( Exception $e ) {
			echo $e->getMessage();
		}
		
	}
	
	/**
	 * Edit a sales rep on given id ($data['id'])
	 * @param array $data
	 */
	public function edit($data) {
		try {
			$result = $this->_connection->update($data, 'id='.$data['id']);
		} catch ( Exception $e ) {
			echo $e->getMessage();
		}
	}
	
	/**
	 * delete salesrep ($data['id'])
	 * @param array $data
	 */
	public function delete($id) {
		try {
			$result = $this->_connection->delete('id='.$id);
		} catch ( Exception $e ) {
			echo $e->getMessage();
		}
	}
	
	/**
	 * 
	 * @param Int $id
	 * @return array datarow
	 */

	public function getSalesRepById($id) {
		try {
			$result = $this->_connection->fetchRow('id='.$id)->toArray();

			
		} catch ( Exception $e ) {
			echo $e->getMessage();
		}
		return $result;
	}
	
	public function getSalesRepByPartyNumber($partyNumber)
	{
		try {
			$sql = $this->_connection->select()
										->setIntegrityCheck(false)
										->from(array('s' => 'bis.tbl_salesrep'), 's.salesRepName')
										->joinLeft(array('cs' => 'bis.tbl_customer_salesrep'), 'cs.salesrep_id = s.id', null)
										->where('cs.customer_partyNumber='.$partyNumber);
			$result = $sql->query()->fetch();
		} catch (Exception $e) {
			echo $e->getMessage();
		}
		return $result;
	}
}